package demo07_AuxiliaryClass;

import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;

/**
 * @author kunkun
 * @className Test03_Semaphore
 * @Description 测试信号量
 * @date 2025/3/6 10:48
 */
public class Test03_Semaphore {

    public static void main(String[] args) throws InterruptedException {

        //1. 新建信号量类
        Semaphore semaphore = new Semaphore(3); //3个车位
        //2. 新建线程类
        for (int i = 0; i < 6; i++) {
            new Thread(()->{
                try {
                    semaphore.acquire(); //获取车位
                    System.out.println(Thread.currentThread().getName() + "get a parking space");
                    TimeUnit.SECONDS.sleep(2); //模拟车辆进入停车位时间
                    System.out.println(Thread.currentThread().getName() + "release");
                } catch (Exception e) {
                    throw new RuntimeException(e);
                } finally {
                    semaphore.release(); //释放车位
                }
            },"线程"+(i+1)).start();
        }


    }

}
